'use client';

import React from 'react';
import { Upload, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { FileMetaType } from '@/types/file';
import { uploadFile } from '@/utils/file';

export interface FileValue {
  fileKey: string;
  fileUrl: string;
}

export interface FileUploadProps {
  value?: FileValue;
  onChange?: (value: FileValue | undefined) => void;
  disabled?: boolean;
  listType?: 'text' | 'picture' | 'picture-card' | 'picture-circle';
  accept?: string;
  maxSize?: number; // MB
  placeholder?: string;
  width?: number | string;
  height?: number | string;
}

const FileUpload: React.FC<FileUploadProps> = ({
  value,
  onChange,
  disabled = false,
  listType = 'picture-card',
  accept = 'image/*',
  maxSize = 5,
  placeholder = '点击上传图片',
  width = '100%',
  height = '100%',
}) => {
  const handleUpload = async (file: File) => {
    // 检查文件大小
    if (file.size / 1024 / 1024 > maxSize) {
      message.error(`文件大小不能超过 ${maxSize}MB`);
      return;
    }

    try {
      const result: FileMetaType = await uploadFile(file);
      const newValue: FileValue = {
        fileKey: result.fileKey || '',
        fileUrl: result.fileUrl || '',
      };
      onChange?.(newValue);
    } catch (error) {
      console.error('上传文件失败:', error);
      message.error('上传文件失败，请重试');
    }
  };

  const handleRemove = () => {
    onChange?.(undefined);
  };

  if (listType === 'picture-card') {
    return (
      <Upload
        name="file"
        listType="picture-card"
        showUploadList={false}
        beforeUpload={() => false} // 阻止默认上传行为
        onChange={async (info) => {
          if (info.file.originFileObj) {
            await handleUpload(info.file.originFileObj);
          }
        }}
        disabled={disabled}
        accept={accept}
      >
        {value?.fileUrl ? (
          <div style={{ position: 'relative', width, height }}>
            <img 
              src={value.fileUrl} 
              alt="上传的图片" 
              style={{ 
                width: '100%', 
                height: '100%', 
                objectFit: 'cover',
                borderRadius: '6px'
              }} 
            />
            {!disabled && (
              <div 
                style={{
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  background: 'rgba(0,0,0,0.5)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  opacity: 0,
                  transition: 'opacity 0.3s',
                  borderRadius: '6px',
                  cursor: 'pointer'
                }}
                className="upload-overlay"
                onMouseEnter={(e) => {
                  e.currentTarget.style.opacity = '1';
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.opacity = '0';
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  handleRemove();
                }}
              >
                <span style={{ color: 'white', fontSize: '12px' }}>点击删除</span>
              </div>
            )}
          </div>
        ) : (
          <div style={{ width, height, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
            <PlusOutlined />
            <div style={{ marginTop: 8, fontSize: '12px' }}>{placeholder}</div>
          </div>
        )}
      </Upload>
    );
  }

  // 其他 listType 的实现可以在这里添加
  return (
    <Upload
      name="file"
      listType={listType}
      beforeUpload={() => false}
      onChange={async (info) => {
        if (info.file.originFileObj) {
          await handleUpload(info.file.originFileObj);
        }
      }}
      disabled={disabled}
      accept={accept}
    >
      {placeholder}
    </Upload>
  );
};

export default FileUpload;
